package com.me.myFramework.aop22.aop121.intercept.method;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.MethodBeforeAdvice;

/**
 * 《AOP-121》：  <br><br>
 *
 * MethodInterceptor 不直接调用目标方法，统一委托给 MethodInvocation（执行器）
 *
 * @author ME
 */
public class MethodBeforeAdviceInterceptor121 implements MethodInterceptor121 {

    private final MethodBeforeAdvice advice;

    public MethodBeforeAdviceInterceptor121(MethodBeforeAdvice advice) {
        this.advice = advice;
    }

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());

        ReflectiveMethodInvocation121 invocation = (ReflectiveMethodInvocation121) mi;
        int index = invocation.getCurrentIndex();
        if (index == invocation.getInterceptorSize() - 1) {
            return mi.getMethod().invoke(mi.getThis(), mi.getArguments());
        }
        else {
            return invocation.getNextInterceptor().invoke(mi);
        }
    }

}
